// *******************************************************************************************************
// # ヘッダー
// *******************************************************************************************************

/*2014.11.27*/
var isUnderIe_head = uaInfo.isIe;
this.simpleSearch = this.simpleSearch || {};

$(function(){
	simpleSearch.KEY = 0;
	
	var $btnOpener = $('#header .btn_easy_search'),
		$target = $('#header_open'),
		opnCls = 'btn_close',
		isOpen = false;

	$btnOpener.on('click', function(e){
		e.preventDefault();
		isOpen = !isOpen;
		$btnOpener.toggleClass(opnCls);
		$target.toggle();
		if (!isOpen) {
			resetDeta();
		};
	});
	$btnOpener.each(function(i){
		if ($(this).hasClass(opnCls)){
			$(this).hide();
		};
	});
	$target.hide();


	var $txtInput = $('#header_open .input_txt input:text'),
		txtDefVal = $txtInput.attr('value');

	$txtInput.focus(function(e){
		$(this).addClass('input-focus');
		if (this.value == this.defaultValue){
			$(this).val('');
		};
	}).blur(function(e){
		if(this.value == ''){
			$(this).val(this.defaultValue);
			$(this).removeClass('input-focus');
		};
	});


	var $litRnt = $('#header_open li.rent'),
		$litPsn = $('#header_open li.parson');
		rntDefVal = $litRnt.find('option').eq(0).val(),
		psnDefVal = $litPsn.find('option').eq(0).val();

	function resetDeta(){
		$txtInput.val(txtDefVal);
		$txtInput.removeClass('input-focus');
		$litRnt.find('select').val(rntDefVal);
		$litRnt.find('.custom_selectInner').text(rntDefVal);
		$litPsn.find('select').val(psnDefVal);
		$litPsn.find('.custom_selectInner').text(psnDefVal);
	};
	resetDeta();

	/*2014.11.27*/
	if(isUnderIe_head){
		function showHeadWrapperControll(){
			$('div#headerWrapper').css({opacity:1});
		}
		showHeadWrapperControll();
	}	
	
/************************
 * 簡単検索
 ************************/		
	function switchButton(){
		enableButton();
		if($('#txtsimpleStation').val() == '' || $('#hidsimpleStation').val() != $('#txtsimpleStation').val()){
			disableButton();
			return;
		}
		if($('select[name=yachin] option:selected').index() <= 0){
			disableButton();
			return;
		}
		if($('select[name=madori] option:selected').index() <= 0){
			disableButton();
			return;
		}
	}
	switchButton();
	$('#txtsimpleStation').attr('autocomplete','off');
	
	$('select[name=yachin]').on('change', function(){	
		switchButton();
	});
	$('select[name=madori]').on('change', function(){
		switchButton();
	});
	
	//ボタン活化
	function disableButton(){		
		$('#btnSimpleSearch').addClass('mod_btn_disabled');
		//$('#btnSimpleSearch').addClass('disabled');
		$('#btnSimpleSearch').removeClass('mod_btn_all_pink');
	}
	//ボタン非活化
	function enableButton(){		
		$('#btnSimpleSearch').removeClass('mod_btn_disabled');
		//$('#btnSimpleSearch').removeClass('disabled');
		$('#btnSimpleSearch').addClass('mod_btn_all_pink');
	}
	
	$('#btnSimpleSearch').removeClass('mod_btn_all_pink');
	$('#btnSimpleSearch').addClass('mod_btn_disabled');
	//$('#btnSimpleSearch').addClass('disabled');
	
	$('#txtsimpleStation').on('propertychange input', function(e){
		switchButton();
				
		if(e.keyCode != undefined && (simpleSearch.KEY == e.keyCode || e.keyCode == 32))
			return;
		simpleSearch.KEY = e.keyCode;
		
		//テキストボックスが変更されたらClear
		if 	($('#hidsimpleStation').val() != $(this).val())
		{
			$('#ulStation').empty();
			$('#stationBox').hide();
		}
		
		//4byte以上→検索		
		if(countJapaneseString($(this).val()) > 1){	
			//console.log($(this).val())
			AjaxEkiSearch($(this).val());			
		}		
		//return false;
	});	
	
	//AutoComplete
//	$('#txtsimpleStation').on('autocompletechange', function(e){
//		switchButton();
//		
//		//テキストボックスが変更されたらClear
//		if 	($('#hidsimpleStation').val() != $(this).val())
//		{
//			$('#ulStation').empty();
//			$('#stationBox').hide();
//		}
//		
//		//4byte以上→検索
//		if(countJapaneseString($(this).val()) > 1){	
//			
//			AjaxEkiSearch($(this).val());			
//		}		
//		return false;
//	});	

	function countJapaneseString(str) { 
	    var r = 0; 
	    for (var i = 0; i < str.length; i++) { 
	        var c = str.charCodeAt(i); 
	        // Shift_JIS: 0x0 ～ 0x80, 0xa0 , 0xa1 ～ 0xdf , 0xfd ～ 0xff 
	        // Unicode : 0x0 ～ 0x80, 0xf8f0, 0xff61 ～ 0xff9f, 0xf8f1 ～ 0xf8f3 
	        if ( (c >= 0x0 && c < 0x81) || (c == 0xf8f0) || (c >= 0xff61 && c < 0xffa0) || (c >= 0xf8f1 && c < 0xf8f4)) { 
	            //r += 1; //全角文字だけカウントする。
	        } else { 
	            r += 1; 
	        } 
	    } 
	    return r; 
	} 
	
	function AjaxEkiSearch(keyword)
	{
		switchButton();
		if (keyword == undefined || keyword == '' )
			return;
	
		
		$.ajax({
			beforeSend: function(xhr){
		    	 xhr.overrideMimeType("text/html;charset=UTF-8");
			},
			type: 'POST',
			url: '/areaajax/geteki/',
			dataType: 'text',
			data:{eki:keyword,likeop:"1"},
			success: function(data) {
				if ($('#txtsimpleStation').val() != keyword){
					AjaxEkiSearch($('#txtsimpleStation').val());
					return;
				}
				if(data != undefined && data != '' && $.trim(data).length > 0){
					$('#ulStation').empty();
					
					//データフォーマット駅（都道府県）|都道府県CDー駅CD;...								
					  var vals = data.split(';');
					  //一つだけ→セット
					  /*
					  if(vals.length == 1){
						  var splitVals = vals[0].split('|');
						  var name = $.trim(splitVals[0]);
						  if(name != '' && name.length > 0){
							  simpleSearch.selectEki(name, $.trim(splitVals[1]));							  
						  }						  
					  }
					  else 
					  */
					  //{
						  for(var i = 0; i < vals.length; i++){
							  var splitVals = vals[i].split('|');
							  $('#ulStation').append('<li><a href="javascript:void(0)" onclick="simpleSearch.selectEki('+ "'" + $.trim(splitVals[0]) + "','" + $.trim(splitVals[1]) + "')" + '"' + '>' + $.trim(splitVals[0]) + '</a></li>')
						  }
						  $('#stationBox').show();  
					  //}					  
				}
				
			},
			error:function() {
				$('#ulStation').empty();
				$('#stationBox').hide();
			}
		});
	}
	//駅選択イベント
	simpleSearch.selectEki = function(name, val){
		$('#txtsimpleStation').val(name);
		$('#hidsimpleStation').val(name);
		$('#hidInput').val(val);
		$('#input-station').val(name);
		$('#ulStation').empty();
		$('#stationBox').hide();
		switchButton();
	}
	$('#btnSimpleSearch').on('click', function(){
		
		if($(this).hasClass('mod_btn_disabled')) {
			return;
		}
		var items = [];
		items.push({name:'search_type', value:'line'});
		
		var vals = $('#hidInput').val().split('-');
		var pref = vals[0];
		var ekis = vals[1].split('.');
		for(var i = 0 ; i < ekis.length ; i++){
			items.push({name:'target_' + String(i), value:pref + '-' + ekis[i]});
		}
		
		//クッキー保存
		var eki = $('#hidsimpleStation').val().split('(')[0];
		CONS.saveSimpleEki(eki + '|' + $('#hidInput').val());
		
		//家賃
		var yachin = $('select[name=yachin]').val().split('-');
		items.push({name:'tinryo1', value:yachin[0]});
		items.push({name:'tinryo2', value:yachin[1]});
		
		//間取り
		var yachin = $('select[name=madori]').val().split('-');
		for(var i = 0;i < yachin.length ; i++){
			items.push({name:yachin[i], value:'on'});
		}
		
		submit('/rstobi/rstobi', 'POST', items);
		
	});
	
	function submit(action, method, values) {
 	   var form = $('<form/>', {
	        action: action,
	        method: method
	    });
	    $.each(values, function() {
	        form.append($('<input/>', {
	            type: 'hidden',
	            name: this.name,
	            value: this.value
	        }));    
	    });
	    form.appendTo('body').submit();
	}
	/*簡単検索*/

});
/*2014.11.27*/
if(!isUnderIe_head){
	$(function(){
		$('div#headerWrapper').css({'opacity':1})
	});
}